import os
import importlib
import xml.etree.ElementTree as ET
from typing import Dict, Any, Optional, Tuple
from .base import Tool

# 工具注册表
TOOLS: Dict[str, Tool] = {}

def register_tool(tool: Tool) -> None:
    """注册工具到全局工具表"""
    global TOOLS
    TOOLS[tool.name] = tool

def execute_tool_call(xml_str: str) -> str:
    """执行工具调用"""
    try:
        # 解析XML
        root = ET.fromstring(xml_str)
        tool_name = root.tag
        
        if tool_name not in TOOLS:
            return f"错误：未找到工具 {tool_name}"
            
        # 获取参数
        params = {}
        for child in root:
            params[child.tag] = child.text
            
        # 执行工具
        tool = TOOLS[tool_name]
        return tool.execute(params)
        
    except ET.ParseError:
        return "错误：无效的工具调用格式"
    except Exception as e:
        return f"执行工具时出错：{str(e)}"

def get_tool_call(content: str) -> Optional[Tuple[str, str]]:
    """从AI响应中提取工具调用信息"""
    for tool_name in TOOLS.keys():
        start_tag = f"<{tool_name}>"
        end_tag = f"</{tool_name}>"
        start = content.find(start_tag)
        end = content.find(end_tag)
        
        if start != -1 and end != -1:
            xml_str = content[start:end + len(end_tag)]
            return tool_name, xml_str
    
    return None

def load_tools() -> None:
    """动态加载tools目录下的所有工具"""
    tools_dir = os.path.dirname(__file__)
    for filename in os.listdir(tools_dir):
        if filename.endswith('.py') and not filename.startswith(('__', 'base')):
            module_name = filename[:-3]
            try:
                module = importlib.import_module(f'.{module_name}', package='tools')
                if hasattr(module, 'TOOL'):
                    tool = getattr(module, 'TOOL')
                    register_tool(tool)
            except Exception as e:
                print(f"加载工具失败: {str(e)}")

# 初始加载所有工具
load_tools()